<?php
namespace app\admin\controller;
use think\facade\Db;
use app\__MODULE__\model\{Bargain as BargainModel,BargainDetail,BargainLog,User};
use app\common\BaseController;

class Bargain extends BaseController{
    

    /**
     * 首页
     */
    public function index(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['title']) && $search['title'] !=''){
            $wheres[] = ['title','like',"%{$search['title']}%"];
        }
        $query  = BargainModel::where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }


        /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = BargainModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }
        /**
     * 上架/下架操作
     * date 2021/3/17 11:20
     */
    public function is_show() {
        $id      = param_check('id');
        $checked = param_check('checked', 0);
        $res = BargainModel::where('id', $id)->update([
            'is_show'        => $checked ? 1 : 0,
            'update_time'   => time()
        ]);
        $res ? json_response(1, '修改成功') : json_response(0, '修改失败');
    }




        /**
     * 添加
     * @return void
     * @author 
     * date 
     */
    public function create(){
        if(request()->isPost()) {
             $data = request()->post();
            try {
                $this->validate($data, [
                    'title' => 'require',
                    'stock' => 'require',
                    'goods_thumb' => 'require',
                    'price' => 'require',
                ], [
                   'title.require'       => '标题不得为空',
                   'stock.require'       => '库存不得为空',
                   'goods_thumb.require' => '图片不得为空',
                   'price.require'       => '价格不得为空',
                ]);
            } catch (\Exception $e) {
                json_response(0,$e->getError());
            }
             $data['start_time'] = strtotime($data['start_time']);
             $data['end_time'] = strtotime($data['end_time']);
             if(strtotime($data['end_time']) < strtotime($data['start_time'])) json_response(0,'结束时间不得早于开始开始');
           if(BargainModel::create($data)) json_response(1,'操作成功');
           json_response(0,'操作失败');
        }
    }



    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
        $id = \param_check('id');
           $data = request()->post();
           try {
            $this->validate($data, [
                'id' => 'require',
                'title' => 'require',
                'stock' => 'require',
                'goods_thumb' => 'require',
                'price' => 'require',
            ], [
                'id.require'       => 'id不得为空',
               'title.require'       => '标题不得为空',
               'stock.require'       => '库存不得为空',
               'goods_thumb.require' => '图片不得为空',
               'price.require'       => '价格不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
            //  if($data['goods_type'] == 2 && !$data['goods_id']) json_response(0,'请选择商品');
             $data['start_time'] = strtotime($data['start_time']);
             $data['end_time'] = strtotime($data['end_time']);
             if(strtotime($data['end_time']) < strtotime($data['start_time'])) json_response(0,'结束时间不得早于开始开始');
           if(BargainModel::update($data,['id'=>$id])) json_response(1,'操作成功');
           json_response(0,'操作失败');
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function delete(){
        $ids = param_check('ids');
        if(!$BargainModel = BargainModel::where('id','in',$ids)->select()) json_response(0,'不存在');
        if($BargainModel->delete()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }



        /**
     * 砍价订单
     * @return [type] [description]
     */
    public function order(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        if(isset($search['aid'])  && $search['aid']!='') $where[] = ['aid', '=', $search['aid']];
        if(isset($search['order_sn'])  && $search['order_sn']!='') $where[] = ['order_sn', '=', $search['order_sn']];
        if(isset($search['status']) && $search['status']!='') $where[] = ['status', '=', $search['status']];
        if(isset($search['pay_status']) && $search['pay_status']!='') $where[] = ['pay_status', '=', $search['pay_status']];
        if(isset($search['user']) && $search['user']!=''){
            $uid = User::where('nickname|mobile','like',"%{$search['user']}%")->column('id');
            $where[] = ['uid','in',$uid];
        }
        $query  = BargainDetail::with(['user','activity'])->where($where);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->append(['status_text','pay_status'])->select();
        $bargain = BargainModel::field('id,title')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'bargain' => $bargain
        ]);
    }

    
        /**
     * 导出excell
     * @return void
     * @author Sam
     *
     */
    public function order_export(){
        $search = request()->param();
        $where = [];
        if(isset($search['aid'])  && $search['aid']!='') $where[] = ['aid', '=', $search['aid']];
        if(isset($search['order_sn'])  && $search['order_sn']!='') $where[] = ['order_sn', '=', $search['order_sn']];
        if(isset($search['status']) && $search['status']!='') $where[] = ['status', '=', $search['status']];
        if(isset($search['pay_status']) && $search['pay_status']!='') $where[] = ['pay_status', '=', $search['pay_status']];
        if(isset($search['user']) && $search['user']!=''){
            $uid = User::where('nickname|mobile','like',"%{$search['user']}%")->column('id');
            $where[] = ['uid','in',$uid];
        }
        $query  = BargainDetail::with(['user','activity'])->append(['status_text','pay_status'])->where($where);
        big_array_to_csv($query,'text.csv',[
            'id'=>'ID',
            'nickname'=>'用户',
            'order_sn'=>'订单号',
            'status_text'=>'砍价状态',
            'pay_status'=>'支付状态',
            'create_time'=>'创建时间',
            'price'=>'砍价价格',
            'title' => ['标题',function($row){
                return $row['activity']['title'];
            }]
        ]);
        
    }


        /**
     * 订单详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function order_detail(int $id): \think\response\Json
    {
        try {
            $row  = BargainDetail::with(['user','activity'])->where('id', $id)->append(['status_text','pay_status'])->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }


        /**
     * 砍价记录
     * @return void
     * @author Sam
     * date 2021-09-09
     */
    public function help_log(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        if(isset($search['aid'])  && $search['aid']!='') $where[] = ['aid', '=', $search['aid']];
        if(isset($search['user']) && $search['user']!=''){
            $uid = User::where('nickname|mobile','like',"%{$search['user']}%")->column('id');
            $where[] = ['uid','in',$uid];
        }
        $query  = BargainLog::with(['help_from','help_to','activity'])->where($where);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        $bargain = BargainModel::field('id,title')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'bargain' => $bargain
        ]);


    }

    /**
     * 砍价记录导出
     * @return void
     * @author Sam
     * @date 2022-04-28
     */
    public function log_export(){
        $search = request()->param();
        $where = [];
        if(isset($search['aid'])  && $search['aid']!='') $where[] = ['aid', '=', $search['aid']];
        if(isset($search['user']) && $search['user']!=''){
            $uid = User::where('nickname|mobile','like',"%{$search['user']}%")->column('id');
            $where[] = ['uid|help_id','in',$uid];
        }
         $db =  BargainLog::with(['help_from','help_to','activity'])->where($where)->order('id desc');
        big_array_to_csv($db, '助力记录', [
            'title'         => '活动',
            'from_nickname' => ['助力人昵称',function($row){
                return iconv('gb2312//ignore', 'utf-8', iconv('utf-8', 'gb2312//ignore', $row['from_nickname']));
            }],
            'from_mobile'   => '助力人手机',
            'to_nickname'   => ['被助力人昵称',function($row){
                return iconv('gb2312//ignore', 'utf-8', iconv('utf-8', 'gb2312//ignore', $row['to_nickname']));
            }],
            'to_mobile'     => '被助力人手机',
            'create_time'   => '助力时间',
            'bargain_price' => '砍掉价格',
            'create_time' => '助力时间'
        ]);
    }

}